#!/user/bin/env python
# -*- coding: utf-8 -*-

import os
#pip install PyMuPDF
import fitz  
#from PyPDF2 import PdfReader, PdfWriter
import hashlib
import re

#fitz  	
def merge_pdfs2(paths, output):	    
    pdf_output = fitz.open()
    total_invoice=0
    print("序号\t金额\t项目名称\t文件名")
    for index, pdf_path in  enumerate(paths):
        invoice,content=extract_invoice_content(pdf_path)
        total_invoice+=invoice
        print("{:02d}\t{}\t{}\t{}".format(index+1, invoice,content,pdf_path))
        try:
            pdf_input = fitz.open(pdf_path)
            pdf_output.insert_pdf(pdf_input)
            pdf_input.close()
        except Exception as e:
            raise
    pdf_output.save(output)
    pdf_output.close()
    print("总金额: %0.02f\n"%total_invoice)
    
    
def calculate_md5(file_path):
    # 创建一个 MD5 哈希对象
    md5_hash = hashlib.md5()
    try:
        # 以二进制只读模式打开文件
        with open(file_path, 'rb') as file:
            # 分块读取文件内容，避免大文件占用过多内存
            for chunk in iter(lambda: file.read(4096), b""):
                # 更新哈希对象
                md5_hash.update(chunk)
        # 获取计算好的 MD5 哈希值，并以十六进制字符串形式返回
        return md5_hash.hexdigest()    
    except Exception as e:
        raise
    
def remove_duplicate_files(paths):    
    md5_dict = {}
    for path in paths:
        md5 = calculate_md5(path)
        if md5:
            if md5 not in md5_dict:
                md5_dict[md5] = path
            else:
                print("Duplacate file: "+path)
    return list(md5_dict.values())


def extract_invoice_content(pdf_path):
    doc = fitz.open(pdf_path)
    max_number=0
    content="未知"
    text_content = ""
    for page in doc:
        txt = page.get_text()
        text_content += txt       
        #rint(txt)
    # 针对发票中「价税合计(小写)」的格式编写正则
    pattern = r'¥(\d+\.\d{2})' 
    match_result = re.findall(pattern, text_content)      
    if match_result:
        max_number = max(float(num) for num in match_result)        
        
    pattern = r'^\*.*'
    match_result = re.findall(pattern, text_content, flags=re.MULTILINE)
    #print(match_result)
    if match_result:
        content = match_result[0]
    return [max_number,content]
    
 
		
if __name__ == '__main__':
    paths = []
    output="merged.pdf"
    if os.path.exists(output):
        os.remove(output)
    for f in os.listdir("./"):
        if f.endswith(".pdf") :
            paths.append(f)            
            #print (extract_invoice_content(f),f)            
    unique_paths = remove_duplicate_files(paths)
    merge_pdfs2(unique_paths, output=output)
    print("Total %d files, merged %d files to %s"%(len(paths),len(unique_paths),output))
    
    
    
    
    